<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import {fetchAddCheckCategory, fetchEditCheckCategory} from '@/service/api';
import { $t } from '@/locales';
import { enableStatusOptions } from '@/constants/business';

defineOptions({
  name: 'CategoryOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.SystemManage.CheckCategory | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: $t('page.check.category.addCategory'),
    edit: $t('page.check.category.editCategory')
  };
  return titles[props.operateType];
});

// type Model = Pick<
//   Api.SystemManage.User,
//   'userName' | 'userGender' | 'nickName' | 'userPhone' | 'userEmail' | 'userRoles' | 'status'
// >;
type Model = Pick<
  Api.SystemManage.CheckCategory,
  "name"  | "id" | "deleteFlag"| "remark"
>;
const model = ref(createDefaultModel());

function createDefaultModel(): Model {
  return {
    deleteFlag: 1,
    name: '',
    id: '',
    remark: ''
  };
}

type RuleKey = Extract<keyof Model, 'name' | 'deleteFlag'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  name: defaultRequiredRule,
  deleteFlag: defaultRequiredRule
};
//
// /** the enabled role options */
// const roleOptions = ref<CommonType.Option<string>[]>([]);
//
// async function getRoleOptions() {
//   const { error, data } = await fetchGetAllRoles();
//
//   if (!error) {
//     const options = data.map(item => ({
//       label: item.roleName,
//       value: item.roleCode
//     }));
//
//     // the mock data does not have the roleCode, so fill it
//     // if the real request, remove the following code
//     // const userRoleOptions = model.value.userRoles.map(item => ({
//     //   label: item,
//     //   value: item
//     // }));
//     // end
//
//     roleOptions.value = [...roleIdOptions, ...options];
//   }
// }

function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model.value, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  console.log(props.rowData);
  try {
    // 验证表单
    await validate();
    // 根据操作类型构造请求参数
    const params = {
      ...model.value
    };// 深拷贝，避免直接修改 model.value
    let response;
    const { id, ...restParams } = params;
    // 根据操作类型调用不同的接口
    switch (props.operateType) {
      case 'add':
        // 调用添加接口
        console.log(params);
        response = await fetchAddCheckCategory(restParams);
        break;
      case 'edit':
        console.log(params);
        response = await fetchEditCheckCategory(params);
        break;
      default:
        throw new Error('未知的操作类型');
    }
    console.log(response);
    // 根据接口返回结果处理
    if (response.error) {
      window.$message?.error($t('common.operationFailed'));
      return;
    }
    // 提示成功
    window.$message?.success($t('common.updateSuccess'));
    // 关闭抽屉
    closeDrawer();
    // 触发父组件的事件，通知更新表格数据
    emit('submitted');
  } catch (error) {
    // 捕获可能的错误
    console.error('Submit Error:', error);
    // 根据错误类型显示不同的提示
    const errorMessage = $t('common.operationFailed');
    window.$message?.error(errorMessage);
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    // getRoleOptions();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem :label="$t('page.check.category.name')">
          <NInput v-model:value="model.name" :placeholder="$t('page.check.category.form.name')" />
        </NFormItem>
        <NFormItem :label="$t('page.check.category.remark')">
          <NInput v-model:value="model.remark" :placeholder="$t('page.check.category.form.remark')" />
        </NFormItem>
        <NFormItem :label="$t('page.check.category.deleteFlag')" path="status">
          <NRadioGroup v-model:value="model.deleteFlag">
            <NRadio v-for="item in enableStatusOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
          </NRadioGroup>
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
